import {SocketIO} from './socketIO'

let socketIO = null

addEventListener('message', ({data}) => {
  const {eventType, content} = data
  switch (eventType) {
    case 'build':
      build(content);
      break;
    case 'connect':
      connect();
      break;
    case 'on':
      on(content);
      break;
    case 'off':
      off(content);
      break;
    case 'emit':
      emit(content);
      break;
    case 'disconnect':
      disconnect();
      break;
    default:
      break;
  }
})

function build({url, token}) {
  socketIO = new SocketIO(url, token)
}

async function connect() {
  try {
    await socketIO.connect()
    postMessage({
      eventType: 'connected'
    })
  } catch (e) {
    postMessage({
      eventType: 'connect_error'
    })
  }
}

function on({event}) {
  socketIO.on(event, data => {
    postMessage({
      eventType: 'result',
      content: {
        event,
        result: data
      }
    })
  })
}

function off({event}) {
  socketIO.off(event)
}

function emit(content) {
  const {event, data} = content
  socketIO.emit(event, data)
}

async function disconnect() {
  try {
    await socketIO.disconnect()
    postMessage({
      eventType: 'disconnected'
    })
  } catch (e) {
    postMessage({
      eventType: 'disconnect_error'
    })
  }

}
